package com.zrrd.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zrrd.common.bo.RoleRuleBo;
import com.zrrd.common.page.RolePageVo;
import com.zrrd.common.vo.RoleVo;
import com.zrrd.entity.Role;
import com.zrrd.entity.RoleRule;
import com.zrrd.mapper.RoleMapper;
import com.zrrd.service.RoleRuleService;
import com.zrrd.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wanjl
 * @since 2024-09-05
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Resource
    private RoleRuleService roleRuleService;


    /**
     * 分页查询角色信息
     *
     * @param page
     * @param limit
     * @return
     */
    @Override
    public RolePageVo findByPage(Integer page, Integer limit) {
        //1.创建要返回的对象
        RolePageVo vo = new RolePageVo();
        //2.开始进行分页
        PageHelper.startPage(page, limit);
        //3.查询角色。并放到PageInfo里面
        PageInfo<Role> pageInfo = new PageInfo(this.list());
        //4.复制集合对象里的元素
        List<RoleVo> roleVoList = pageInfo.getList().stream().map(role -> {
            RoleVo roleVo = new RoleVo();
            BeanUtils.copyProperties(role, roleVo);

            //根据角色id查询角色应该具备的权限列表
            List<RoleRuleBo> boList = getRuleListByRoleId(role.getId());
            roleVo.setRules(boList);

            return roleVo;
        }).collect(Collectors.toList());

        vo.setList(roleVoList);
        vo.setTotalCount(pageInfo.getTotal());


        return vo;
    }

    private List<RoleRuleBo> getRuleListByRoleId(Integer roleId) {
        List<RoleRule> list = roleRuleService.lambdaQuery().eq(roleId != null, RoleRule::getRoleId, roleId).list();
        return list.stream().map(roleRule -> new RoleRuleBo(roleRule.getRuleId(),roleRule)).collect(Collectors.toList());
    }
}
